package com.wthink.hzgj.camera.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.wthink.hzgj.camera.data.Camera
import com.wthink.hzgj.data.Result
import com.wthink.hzgj.data.domain.CameraInfo
import com.wthink.hzgj.service.DevService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

class CameraViewModel : ViewModel() {

    val cameraList = MutableLiveData(emptyList<Camera>())

    fun start() {
        viewModelScope.launch(Dispatchers.IO) {
            while (isActive) {
                val cameraInfoRet = DevService.queryCamera()
                if (cameraInfoRet is Result.Success) {
                    val cameraInfo = cameraInfoRet.data as CameraInfo
                    val list = cameraInfo.cameraList.map {
                        Camera(it, cameraInfo.videoList.contains(it))
                    }
                    cameraList.postValue(list)
                }
                delay(1000)
            }
        }
    }

    fun select(camera: Camera) {
        val list = cameraList.value!!.filter {
            if (it.name.equals(camera.name)) {
                !it.selected
            } else {
                it.selected
            }
        }.map { it.name }.toList()

        viewModelScope.launch(Dispatchers.IO) {
            DevService.setCamera(list)
        }
    }
}
